import { FC, useState } from "react";

import { Toast } from "antd-mobile";

import styled from "./styled.module.scss"; // FIXED: 这种写法存在样式污染后期解决

interface Props {}
const Index: FC<Props> = () => {
  // 表单数据
  const [formData, setFormData] = useState({
    mobile: "15021459079",
    code: "",
  });
  const onFormDataUpdate = (e: React.ChangeEvent<HTMLInputElement>) => {
    // 1 修改内存
    // formData.键 = 数据
    formData[e.target.name as "mobile" | "code"] = e.target.value;
    // 2 同步视图
    // setFormData(formData)
    setFormData({ ...formData });
  };
  // 短信倒计时
  // 1 定义模型 t、num、disabled、msg =》 视图使用
  const [sms, setSms] = useState({
    t: 0 as any,
    num: 10,
    disabled: false,
    msg: "获取验证码",
  });
  // 2 绑定点击事件
  const onSendSms = () => {
    // - 2.1 先判断手机号是否正确
    if (!/^1\d{10}$/.test(formData.mobile)) {
      // alert("手机号有瑕疵");
      Toast.show({
        icon: "fail",
        content: "手机号有瑕疵",
      });
      return;
    }
    // - 2.2 立马-1
    sms.disabled = true;
    sms.num--;
    sms.msg = `剩余${sms.num}s`;
    setSms({ ...sms });
    // - 2.3 定时器-1
    sms.t = setInterval(() => {
      if (sms.num <= 1) {
        clearInterval(sms.t);
        sms.disabled = false;
        sms.msg = "获取验证码";
        sms.num = 10;
        setSms({ ...sms }); // 切记别忘了同步
        return;
      }
      sms.num--;
      sms.msg = `剩余${sms.num}s`;
      setSms({ ...sms }); // 切记别忘了同步
    }, 1000);
    setSms({ ...sms });
    // - 2.4 请求接口
    alert("请求接口");
  };

  // 渲染
  return (
    <div className={styled.login}>
      {/* 
      明确：以前的不支持了 <img src="../../assets/logo1.jpg" alt="" />  
      必须：写 { require(路径) }
      留心：切记不能有引号包着大括号
      */}
      <img src={require("../../assets/logo1.jpg")} alt="" />
      <div className={`${styled.item} ${styled.mobile}`}>
        <input
          type="text"
          placeholder="手机号"
          name="mobile"
          value={formData.mobile}
          onChange={onFormDataUpdate}
        />
        <button disabled={sms.disabled} onClick={onSendSms}>
          {sms.msg}
        </button>
      </div>
      <div className={styled.item}>
        <input
          type="text"
          placeholder="验证码"
          name="code"
          value={formData.code}
          onChange={onFormDataUpdate}
        />
      </div>
      <div className={`${styled.item} ${styled.loginBtn}`}>
        <button>登录</button>
      </div>
      <p>收不到验证码</p>
    </div>
  );
};

export default Index;
